//
//  54. 旋转矩形.swift
//  Top600
//
//  Created by rjb on 2021/7/30.
//

import Foundation
class Solution54 {
    func spiralOrder(_ matrix: [[Int]]) -> [Int] {
        var result: [Int] = []
        
        var visited: [[Bool]] = Array(repeating: Array(repeating: false, count: matrix[0].count), count: matrix.count)
        let total = matrix.count * matrix[0].count
        let rows = matrix.count
        let columns = matrix[0].count
        
        let directions = [
            [0,1],
            [1,0],
            [0,-1],
            [-1,0]
        ]
        var row = 0
        var column = 0
        var directionIndex = 0
        // 结束点total非常关键
        for _ in 0..<total {
            result.append(matrix[row][column])
            visited[row][column] = true
            // 计算可能的下一个位置
            let nextRow = row + directions[directionIndex][0]
            let nextColumn = column + directions[directionIndex][1]
            if nextRow < 0
                || nextRow >= rows
                || nextColumn < 0
                || nextColumn >= columns
                || visited[nextRow][nextColumn] {
                directionIndex = (directionIndex + 1) % 4
            }
            // 计算真正的位置
            row += directions[directionIndex][0]
            column += directions[directionIndex][1]
        }
        return result
    }
    static func test() {
        let solution = Solution54()
        let matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
        let result = solution.spiralOrder(matrix)
        print(result)
    }
}
